package com.yzh.springboot_rbac.service.impl;

import com.yzh.springboot_rbac.entity.Role;
import com.yzh.springboot_rbac.mapper.RoleMapper;
import com.yzh.springboot_rbac.mapper.RoleMenuMapper;
import com.yzh.springboot_rbac.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean isAddRole(Role role, Integer menuId) throws Exception {
        List<Role> roles = roleMapper.selectRoleByCondition(role);
        System.out.println(roles);
        if (roles.isEmpty()) {
            int row = roleMapper.insertRole(role);
            if (row > 0) {
                Integer roleId = role.getRoleId();
                if (roleId == null) {
                    throw new Exception("插入角色成功，但未获取到 userId");
                }
                int i = roleMenuMapper.insertRoleMenuId(roleId, menuId);
                if (i <= 0) {
                    throw new Exception("角色菜单关系表更新失败");
                }
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    @Override
    public List<Role> selectRoleByCondition(Role role) {
        List<Role> roles = roleMapper.selectRoleByCondition(role);
        if (roles != null) {
            return roles;
        } else {
            return null;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean isUpdateRole(Role role, Integer menuId) throws Exception {
        int row = roleMapper.updateRole(role);
        if (row > 0) {
            Integer roleId = role.getRoleId();
            int i = roleMenuMapper.updateRoleMenuId(roleId, menuId);
            if (i > 0) {
                return true;
            } else {
                throw new Exception("更新角色菜单表失败，触发回滚");
            }
        } else {
            return false;
        }
    }

    @Override
    public Boolean deleteRole(Role role) throws Exception {
        int row = roleMapper.deleteRole(role);
        if (row > 0) {
            int row2 = roleMenuMapper.deleteRoleMenuId(role);
            if (row2 > 0) {
                return true;
            } else {
                throw new Exception("删除角色-菜单关系表失败，触发回滚");
            }
        } else {
            return false;
        }
    }
}
